#include <bits/stdc++.h>
using namespace std;
#define int long long

void solve() {
    int n, m;
    cin >> n >> m;
    int x;
    vector<pair<int, int>> a;
    for(int i = 0; i < n; i++) {
        int sum = 0, t = 0;
        for(int j = 0; j < m; j++) {
            cin >> x;
            t += x;
            sum += t;
        } 
        a.push_back({t, sum});
    }
    sort(a.begin(), a.end(), greater<pair<int, int>>());
    int ans = 0, sum = 0;
    for(int i = 0; i < n; i++) {
        ans = ans + a[i].second + sum;
        sum += a[i].first * m;
    }
    cout << ans << endl;
}

signed main() {
    int t; cin >> t;
    while(t--) {
        solve();
    }
    return 0;
}